<?php

class Xzsdsplus_Importplus_Model_Convert_Adapter_Product extends Mage_Catalog_Model_Convert_Adapter_Product {
    
    private $_attributeCode = 'diamond_size';
    
    private function _getSku(&$importData) {
        $importData['name'] = $importData['sku'];
        $importData['sku'] = $importData['sku'] .'-'. str_replace(array(' ','.'),array('-','-'), $importData['Qualities']);
        return true;
    }
    
    private function _getConfigurable($importData) { // not &
        $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $importData['sku']);
        if(!$product){
//Mage::log('new configurable');
            $importData['name'] = $importData['sku'];
            $importData['config_attributes'] = $this->_attributeCode;
            $importData['visibility'] = 'Catalog, Search';
            $importData['type'] = 'configurable';
            $product = $this->_saveProduct($importData);
            $product = Mage::getModel('catalog/product')->load($product->getId());// to configurable type
//Mage::log('$configurable:'.$product->getId());
        }
        return $product;
    }
    
    private function _getAttributeId() {
        $eavAttributeModel = Mage::getModel('eav/entity_attribute');
        $id = $eavAttributeModel->getIdByCode('catalog_product',$this->_attributeCode);
        if (!$id) {
            throw new Exception('cant find attribute code :'. $this->_attributeCode);
        }
        return  $id;
    }
    
    private function _arrayToIds(&$ary) {
        $ids = array();
        foreach($ary as $val) {
            $ids[$val] = array('position'=>0);
        }
        return $ids;
    }
    
    private function _getOptionId(&$importData) {
        
        //$value = $importData['sku']. ' '. $importData['Qualities'];
        $value = $importData['Qualities'];
        $attribId = $this->_getAttributeId();
        $module = Mage::getResourceModel('eav/entity_attribute_option');
        $optionTable  = $module->getTable('attribute_option');
        $optionValueTable   = $module->getTable('attribute_option_value');
        $read = Mage::getSingleton('core/resource')->getConnection('core_read');
        $write = Mage::getSingleton('core/resource')->getConnection('core_write');
        $optionValInsert = true;
        $optionValId = '';
        
        $select = $read->select()->from(array('vals' => $optionValueTable))
                ->join(array('opt' => $optionTable),'opt.option_id=vals.option_id')
                ->where('opt.attribute_id=?', $attribId);

        $optionValData = $read->fetchAll($select);

        foreach ($optionValData as $valData) {
            if (strcasecmp(trim($valData['value']), $value) === 0) {
                $optionValInsert = false;
                $optionValId = $valData['option_id'];
//Mage::log('$optionValInsert : false');
            }
        }

        if ($optionValInsert) {
            $data = array(
                'attribute_id'  => $attribId,
                'sort_order'    => 0,
            );

            $write->insert($optionTable, $data);
            $intOptionId = $write->lastInsertId();

            $store = $this->getStoreById($this->getBatchParams('store'));
            $data = array(
                'option_id' => $intOptionId,
                'store_id'  => $store->getId(),
                'value'     => $value,
            );
        
            $write->insert($optionValueTable, $data);
            $optionValId =  $write->lastInsertId();
        }
        return $value;
    }
    
    public function saveRow(array $importData) {
        
        $status = Mage::getSingleton('importplus/status');
        
        if (!$status->getStatus()) {
            return parent::saveRow($importData);
        }
        
        if(empty($importData['sku'])) {
            Mage::throwException('sku error!');
            return true;
        }
        
       $configurable = $this->_getConfigurable($importData);
        
        $this->_getSku($importData);
        $option = $this->_getOptionId($importData);
        $importData['type'] = 'simple';
        $importData['visibility'] = 'Not Visible Individually';
        $importData[$this->_attributeCode] = $option;
        $product = $this->_saveProduct($importData);
        
        if ($configurable && $product) {
//Mage::log('insert product');
            //Mage_Catalog_Model_Product_Type_Configurable
            $module = Mage::getSingleton('catalog/product_type_configurable');
            $products = $module->getUsedProductIds($configurable);
//Mage::log($products);
            if (empty($products)) {
                $products = $product->getSku();
//Mage::log('skustoids :');
//Mage::log($this->skusToIds( $products, $configurable));
                $configurable->setConfigurableProductsData( $this->skusToIds( $products, $configurable));
                $configurable->save();
            } else {
                $id = $product->getId();
                if (!in_array($id, $products)){
                    $products[] = $id;
                    $products = $this->_arrayToIds($products);
                    $configurable->setConfigurableProductsData($products);
                    $configurable->save();
//Mage::log('add product:');
//Mage::log($products);
                }
            }
        }
        return true;
    }
    
    private function _saveProduct(&$importData){
//Mage::log($importData);
        $status = Mage::getSingleton('importplus/status');
        $qty = $status->getDefaultQty();
        $category_ids = $status->getCategoryIds();
        
        $importData['attribute_set'] = 'diamond';
        $importData['qty'] = $qty;
        $importData['category_ids'] = $category_ids;
        $importData['description'] ='  ';
        $importData['short_description'] ='  ';
        $importData['weight'] = $importData['Weight'] ;
        $importData['price'] = '0';
        $importData['tax_class_id'] = 'None';
        $importData['websites'] = 'base';
        $importData['status'] = 'Enabled';
        $importData['is_in_stock'] = '1';
        $importData['Metal Types:radio:1:0'] = '14k White:fixed:0.0000::0|14k Yellow:fixed:0.0000::0';
        
        $product = $this->getProductModel();
        $product->setData ( array () );
        
        if ($stockItem = $product->getStockItem ()) {
            $stockItem->setData ( array () );
        }
        
        //$product = $this->getProductModel()->reset();
        
         if(!empty($importData['18k']) && is_numeric($importData['18k']))
            $importData['Metal Types:radio:1:0'] .= '|18k White:fixed:'.$importData['18k'].'::0|18k Yellow:fixed:'.$importData['18k'].'::0';
         if(!empty($importData['Platinum']) && is_numeric($importData['Platinum']))
            $importData['Metal Types:radio:1:0'] .= '|Platinum:fixed:'.$importData['Platinum'].'::0';

        //$importData['Select Diamond Quality:drop_down:1:10'] = 'Mounting Only:fixed:'.$importData['Mounting'].'::0';  Mounting only price
        $importData['Select Diamond Quality:drop_down:1:10'] = '';
        
        if(!empty($importData['SI1 - SI2']) && is_numeric($importData['SI1 - SI2']))
            $importData['Select Diamond Quality:drop_down:1:10'] .= 'SI1-SI2 G/H Color:fixed:'.$importData['SI1 - SI2'].'::0';
        
        if(!empty($importData['SI2 - SI3']) && is_numeric($importData['SI2 - SI3']))
            $importData['Select Diamond Quality:drop_down:1:10'] .= '|SI2-SI3 J/K Color:fixed:'.$importData['SI2 - SI3'].'::0';
        
        if(!empty($importData['SI3 - I1']) && is_numeric($importData['SI3 - I1']))
            $importData['Select Diamond Quality:drop_down:1:10'] .= '|SI3-I2 J/K Color:fixed:'.$importData['SI3 - I1'].'::0';
        
        if(!empty($importData['VS1']) && is_numeric($importData['VS1']))
            $importData['Select Diamond Quality:drop_down:1:10'] .= '|VS1-VS2 G Color:fixed:'.$importData['VS1'].'::0';
        
        if(!empty($importData['VS2 - SI1']) && is_numeric($importData['VS2 - SI1']))
            $importData['Select Diamond Quality:drop_down:1:10'] .= '|VS1-VS2 G/H Color:fixed:'.$importData['VS2 - SI1'].'::0';

        if (empty($importData['store'])) {
            if (!is_null($this->getBatchParams('store'))) {
                $store = $this->getStoreById($this->getBatchParams('store'));
            } else {
                $message = Mage::helper('catalog')->__(
                    'Skipping import row, required field "%s" is not defined.',
                    'store'
                );
                Mage::throwException($message);
            }
        } else {
            $store = $this->getStoreByCode($importData['store']);
        }

        if ($store === false) {
            $message = Mage::helper('catalog')->__(
                'Skipping import row, store "%s" field does not exist.',
                $importData['store']
            );
            Mage::throwException($message);
        }

        if (empty($importData['sku'])) {
            $message = Mage::helper('catalog')->__('Skipping import row, required field "%s" is not defined.', 'sku');
            Mage::throwException($message);
        }
        $product->setStoreId($store->getId());
        $productId = $product->getIdBySku($importData['sku']);

        if ($productId) {
            $product->load($productId);
        }

        
        $productTypes = $this->getProductTypes();
        $productAttributeSets = $this->getProductAttributeSets();

        /**
         * Check product define type
         */
        if (empty($importData['type']) || !isset($productTypes[strtolower($importData['type'])])) {
            $value = isset($importData['type']) ? $importData['type'] : '';
            $message = Mage::helper('catalog')->__(
                'Skip import row, is not valid value "%s" for field "%s"',
                $value,
                'type'
            );
            Mage::throwException($message);
        }
        $product->setTypeId($productTypes[strtolower($importData['type'])]);
        /**
         * Check product define attribute set
         */
        if (empty($importData['attribute_set']) || !isset($productAttributeSets[$importData['attribute_set']])) {
            $value = isset($importData['attribute_set']) ? $importData['attribute_set'] : '';
            $message = Mage::helper('catalog')->__(
                'Skip import row, the value "%s" is invalid for field "%s"',
                $value,
                'attribute_set'
            );
            Mage::throwException($message);
        }
        $product->setAttributeSetId($productAttributeSets[$importData['attribute_set']]);

        foreach ($this->_requiredFields as $field) {
            $attribute = $this->getAttribute($field);
            if (!isset($importData[$field]) && $attribute && $attribute->getIsRequired()) {
                $message = Mage::helper('catalog')->__(
                    'Skipping import row, required field "%s" for new products is not defined.',
                    $field
                );
                Mage::throwException($message);
            }
        }
        
        $currentproducttype = $importData ['type'];
        
        if ($importData ['type'] == 'configurable' && isset ( $importData ['config_attributes'] )) {
            
            $product->setCanSaveConfigurableAttributes ( true );
            $configAttributeCodes = $this->userCSVDataAsArray ( $importData ['config_attributes'] );
            $usingAttributeIds = array ();
            
            $configAttributes = array();
            foreach ( $configAttributeCodes as $attributeCode ) {
                $attribute = $product->getResource ()->getAttribute ( $attributeCode );
                if ($product->getTypeInstance ()->canUseAttribute ( $attribute )) {
                    $configAttributes[] = array(
                        'id'             => $attribute->getId(),
                        'label'          => $attribute->getFrontend_label(),
                        'use_default'    => $attribute->getIs_User_Defined(),
                        'position'       => $attribute->getPosition(),
                        'values'         => $attribute->getPrices() ? $attribute->getPrices() : array(),
                        'attribute_id'   => $attribute->getAttributeId(),
                        'attribute_code' => $attribute->getAttributeCode(),
                        'frontend_label' => $attribute->getFrontend_label(),
                        'store_label'    => $attribute->getFrontend_label(),
                    );
                    $usingAttributeIds [] = $attribute->getAttributeId ();
                }
            }

            if (! empty ( $usingAttributeIds )) {

                $product->getTypeInstance ()->setUsedProductAttributeIds ( $usingAttributeIds );
                
                $configAttributes_new = $product->getTypeInstance ()->getConfigurableAttributesAsArray ($product);
                for($i = 0; $i < count($configAttributes_new); $i++) {
                    $configAttributes_new[$i]['label'] =  $configAttributes[$i]['label'];
                }
                
                $product->setConfigurableAttributesData ($configAttributes_new);
                Mage::log('setConfigurableAttributesData:');
                Mage::log($product->getTypeInstance ()->getConfigurableAttributesAsArray ($product));
                $product->setCanSaveConfigurableAttributes ( true );
                $product->setCanSaveCustomOptions ( true );
            }
            if (isset ( $importData ['associated'] )) {
                $product->setConfigurableProductsData ( $this->skusToIds ( $importData ['associated'], $product ) );
            }
        }

        $this->setProductTypeInstance($product);

        if (!empty($importData['category_ids'])) {
            $product->setCategoryIds($importData['category_ids']);
        }

        foreach ($this->_ignoreFields as $field) {
            if (isset($importData[$field])) {
                unset($importData[$field]);
            }
        }

        if ($store->getId() != 0) {
            $websiteIds = $product->getWebsiteIds();
            if (!is_array($websiteIds)) {
                $websiteIds = array();
            }
            if (!in_array($store->getWebsiteId(), $websiteIds)) {
                $websiteIds[] = $store->getWebsiteId();
            }
            $product->setWebsiteIds($websiteIds);
        }

        if (isset($importData['websites'])) {
            $websiteIds = $product->getWebsiteIds();
            if (!is_array($websiteIds) || !$store->getId()) {
                $websiteIds = array();
            }
            $websiteCodes = explode(',', $importData['websites']);
            foreach ($websiteCodes as $websiteCode) {
                try {
                    $website = Mage::app()->getWebsite(trim($websiteCode));
                    if (!in_array($website->getId(), $websiteIds)) {
                        $websiteIds[] = $website->getId();
                    }
                }
                catch (Exception $e) {}
            }
            $product->setWebsiteIds($websiteIds);
            unset($websiteIds);
        }

        foreach ($importData as $field => $value) {
            if (in_array($field, $this->_inventoryFields)) {
                continue;
            }
            if (is_null($value)) {
                continue;
            }

            $attribute = $this->getAttribute($field);
            if (!$attribute) {
                continue;
            }

            $isArray = false;
            $setValue = $value;

            if ($attribute->getFrontendInput() == 'multiselect') {
                $value = explode(self::MULTI_DELIMITER, $value);
                $isArray = true;
                $setValue = array();
            }

            if ($value && $attribute->getBackendType() == 'decimal') {
                $setValue = $this->getNumber($value);
            }

            if ($attribute->usesSource()) {
                $options = $attribute->getSource()->getAllOptions(false);

                if ($isArray) {
                    foreach ($options as $item) {
                        if (in_array($item['label'], $value)) {
                            $setValue[] = $item['value'];
                        }
                    }
                } else {
                    $setValue = false;
                    foreach ($options as $item) {
                        if ($item['label'] == $value) {
                            $setValue = $item['value'];
                        }
                    }
                }
            }

            $product->setData($field, $setValue);
        }

        if (!$product->getVisibility()) {
            $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
        }

        

        $custom_options = array ();
        
        foreach ( $importData as $field => $value ) {

            if (in_array ( $field, $this->_imageFields )) {
                continue;
            }
            
            $attribute = $this->getAttribute ( $field );
            if (! $attribute) {
                
                if (strpos ( $field, ':' ) !== FALSE && strlen ( $value )) {
                    $values = explode ( '|', $value );
                    if (count ( $values ) > 0) {
                        $iscustomoptions = "true";
                        
                        foreach ( $values as $v ) {
                            $parts = explode ( ':', $v );
                            $title = $parts [0];
                        }
                        
                        @list ( $title, $type, $is_required, $sort_order ) = explode ( ':', $field );
                        $title2 = ucfirst ( str_replace ( '_', ' ', $title ) );
                        $custom_options [] = array ('is_delete' => 0, 'title' => $title2, 'previous_group' => '', 'previous_type' => '', 'type' => $type, 'is_require' => $is_required, 'sort_order' => $sort_order, 'values' => array () );
                        foreach ( $values as $v ) {
                            $parts = explode ( ':', $v );
                            $title = $parts [0];
                            if (count ( $parts ) > 1) {
                                $price_type = $parts [1];
                            } else {
                                $price_type = 'fixed';
                            }
                            if (count ( $parts ) > 2) {
                                $price = $parts [2];
                            } else {
                                $price = 0;
                            }
                            if (count ( $parts ) > 3) {
                                $sku = $parts [3];
                            } else {
                                $sku = '';
                            }
                            if (count ( $parts ) > 4) {
                                $sort_order = $parts [4];
                            } else {
                                $sort_order = 0;
                            }
                            if (count ( $parts ) > 5) {
                                $file_extension = $parts [5];
                            } else {
                                $file_extension = '';
                            }
                            if (count ( $parts ) > 6) {
                                $image_size_x = $parts [6];
                            } else {
                                $image_size_x = '';
                            }
                            if (count ( $parts ) > 7) {
                                $image_size_y = $parts [7];
                            } else {
                                $image_size_y = '';
                            }
                            switch ($type) {
                                case 'file':
                                    $custom_options [count ( $custom_options ) - 1] ['price_type'] = $price_type;
                                    $custom_options [count ( $custom_options ) - 1] ['price'] = $price;
                                    $custom_options [count ( $custom_options ) - 1] ['sku'] = $sku;
                                    $custom_options [count ( $custom_options ) - 1] ['file_extension'] = $file_extension;
                                    $custom_options [count ( $custom_options ) - 1] ['image_size_x'] = $image_size_x;
                                    $custom_options [count ( $custom_options ) - 1] ['image_size_y'] = $image_size_y;
                                    break;
                                
                                case 'field' :
                                case 'area' :
                                    $custom_options [count ( $custom_options ) - 1] ['max_characters'] = $sort_order;
                                /* NO BREAK */
                                
                                case 'date' :
                                case 'date_time' :
                                case 'time' :
                                    $custom_options [count ( $custom_options ) - 1] ['price_type'] = $price_type;
                                    $custom_options [count ( $custom_options ) - 1] ['price'] = $price;
                                    $custom_options [count ( $custom_options ) - 1] ['sku'] = $sku;
                                    break;
                                
                                case 'drop_down' :
                                case 'radio' :
                                case 'checkbox' :
                                case 'multiple' :
                                default :
                                    $custom_options [count ( $custom_options ) - 1] ['values'] [] = array ('is_delete' => 0, 'title' => $title, 'option_type_id' => - 1, 'price_type' => $price_type, 'price' => $price, 'sku' => $sku, 'sort_order' => $sort_order );
                                    break;
                            }
                        }
                    }
                }

                continue;
            }
            
            $isArray = false;
            $setValue = $value;
            
            if ($attribute->getFrontendInput () == 'multiselect') {
                $value = explode( self::MULTI_DELIMITER, $value );
                $isArray = true;
                $setValue = array ();
            }
            
            if ($value && $attribute->getBackendType () == 'decimal') {
                $setValue = $this->getNumber ( $value );
            }
            
            if ($attribute->usesSource ()) {
                $options = $attribute->getSource ()
                    ->getAllOptions ( false );
                
                if ($isArray) {
                    foreach ( $options as $item ) {
                        if (in_array ( $item ['label'], $value )) {
                            $setValue [] = $item ['value'];
                        }
                    }
                } else {
                    $setValue = null;
                    foreach ( $options as $item ) {
                        if ($item ['label'] == $value) {
                            $setValue = $item ['value'];
                        }
                    }
                }
            }
            
            $product->setData ( $field, $setValue );
        }
        
        
        $stockData = array();
        $inventoryFields = isset($this->_inventoryFieldsProductTypes[$product->getTypeId()])
            ? $this->_inventoryFieldsProductTypes[$product->getTypeId()]
            : array();
        foreach ($inventoryFields as $field) {
            if (isset($importData[$field])) {
                    $stockData[$field] = $importData[$field];
            }
        }

        $product->setStockData($stockData);
        
        $mediaGalleryBackendModel = $this->getAttribute('media_gallery')->getBackend();

        $arrayToMassAdd = array();

        foreach ($product->getMediaAttributes() as $mediaAttributeCode => $mediaAttribute) {
            if (isset($importData[$mediaAttributeCode])) {
                $file = trim($importData[$mediaAttributeCode]);
                if (!empty($file) && !$mediaGalleryBackendModel->getImage($product, $file)) {
                    $arrayToMassAdd[] = array('file' => trim($file), 'mediaAttribute' => $mediaAttributeCode);
                }
            }
        }

        $addedFilesCorrespondence = $mediaGalleryBackendModel->addImagesWithDifferentMediaAttributes(
            $product,
            $arrayToMassAdd, Mage::getBaseDir('media') . DS . 'import',
            false,
            false
        );

        foreach ($product->getMediaAttributes() as $mediaAttributeCode => $mediaAttribute) {
            $addedFile = '';
            if (isset($importData[$mediaAttributeCode . '_label'])) {
                $fileLabel = trim($importData[$mediaAttributeCode . '_label']);
                if (isset($importData[$mediaAttributeCode])) {
                    $keyInAddedFile = array_search($importData[$mediaAttributeCode],
                        $addedFilesCorrespondence['alreadyAddedFiles']);
                    if ($keyInAddedFile !== false) {
                        $addedFile = $addedFilesCorrespondence['alreadyAddedFilesNames'][$keyInAddedFile];
                    }
                }

                if (!$addedFile) {
                    $addedFile = $product->getData($mediaAttributeCode);
                }
                if ($fileLabel && $addedFile) {
                    $mediaGalleryBackendModel->updateImage($product, $addedFile, array('label' => $fileLabel));
                }
            }
        }

        $product->setIsMassupdate(true);
        $product->setExcludeUrlRewrite(true);
        //Mage::log($product);
        $product->save();
        
        if (count ( $custom_options )) {
            foreach ( $product->getOptions () as $o ) {
                if ($this->_chkTitle($o->getTitle(), $custom_options)) {
                    $o->getValueInstance ()->deleteValue ( $o->getId () );
                    $o->deletePrices ( $o->getId () );
                    $o->deleteTitles ( $o->getId () );
                    $o->delete ();
                }
            }
        
        /* Add the custom options specified in the CSV import file */
        
            foreach ( $custom_options as $option ) {
                try {
                    $opt = Mage::getModel ( 'catalog/product_option' );
                    $opt->setProduct ( $product );
                    $opt->addOption ( $option );
                    $opt->saveOptions ();
                } catch ( Exception $e ) {
                }
            }
        }
        
        if ($iscustomoptions == "true") {

            if ($currentproducttype == "simple") {
                $prefix = Mage::getConfig ()->getNode ( 'global/resources/db/table_prefix' );
                $fixOptions = Mage::getSingleton ( 'core/resource' )->getConnection ( 'core_write' );
                // now $write is an instance of Zend_Db_Adapter_Abstract 
                $fixOptions->query ( "UPDATE " . $prefix . "catalog_product_entity SET has_options = 1 WHERE type_id = 'simple' AND entity_id IN (SELECT distinct(product_id) FROM " . $prefix . "catalog_product_option)" );
            
            } else if ($currentproducttype == "configurable") {
                $prefix = Mage::getConfig ()->getNode ( 'global/resources/db/table_prefix' );
                $fixOptions = Mage::getSingleton ( 'core/resource' )->getConnection ( 'core_write' );
                // now $write is an instance of Zend_Db_Adapter_Abstract 
                $fixOptions->query ( "UPDATE " . $prefix . "catalog_product_entity SET has_options = 1 WHERE type_id = 'configurable' AND entity_id IN (SELECT distinct(product_id) FROM " . $prefix . "catalog_product_option)" );
            }
        }
        Mage::log('$product:'.$product->getId());
        return $product;
    }
  
    
   /**
     * Prepare stock item data for save
     *
     * @param Mage_CatalogInventory_Model_Stock_Item $item
     * @param Mage_Catalog_Model_Product $product
     * @return Mage_CatalogInventory_Model_Observer
     */
    
    protected function _prepareItemForSave($item, $product) {
        $item->addData($product->getStockData())
            ->setProduct($product)
            ->setProductId($product->getId())
            ->setStockId($item->getStockId());
        if (!is_null($product->getData('stock_data/min_qty'))
            && is_null($product->getData('stock_data/use_config_min_qty'))) {
            $item->setData('use_config_min_qty', false);
        }
        if (!is_null($product->getData('stock_data/min_sale_qty'))
            && is_null($product->getData('stock_data/use_config_min_sale_qty'))) {
            $item->setData('use_config_min_sale_qty', false);
        }
        if (!is_null($product->getData('stock_data/max_sale_qty'))
            && is_null($product->getData('stock_data/use_config_max_sale_qty'))) {
            $item->setData('use_config_max_sale_qty', false);
        }
        if (!is_null($product->getData('stock_data/backorders'))
            && is_null($product->getData('stock_data/use_config_backorders'))) {
            $item->setData('use_config_backorders', false);
        }
        if (!is_null($product->getData('stock_data/notify_stock_qty'))
            && is_null($product->getData('stock_data/use_config_notify_stock_qty'))) {
            $item->setData('use_config_notify_stock_qty', false);
        }
        return $this;
    } 

    protected function userCSVDataAsArray($data) {
//Mage::log('$data:');
//Mage::log($data);
        return explode ( ',', str_replace ( " ", "", $data ) );
    }
    
    protected function skusToIds($userData, $product) {
        $productIds = array ();
        foreach ( $this->userCSVDataAsArray ( $userData ) as $oneSku ) {
            if (($a_sku = ( int ) $product->getIdBySku ( $oneSku )) > 0) {
                parse_str ( "position=", $productIds [$a_sku] );
            }
        }
        return $productIds;
    }
    
    protected $_categoryCache = array ();
    
    protected function _addCategories($categories, $store) {
        // $rootId = $store->getRootCategoryId();
        // $rootId = Mage::app()->getStore()->getRootCategoryId();
        $rootId = 2; // our store's root category id
        if (! $rootId) {
            return array ();
        }
        $rootPath = '1/' . $rootId;
        if (empty ( $this->_categoryCache [$store->getId ()] )) {
            $collection = Mage::getModel ( 'catalog/category' )->getCollection ()
                ->setStore ( $store )
                ->addAttributeToSelect ( 'name' );
            $collection->getSelect ()
                ->where ( "path like '" . $rootPath . "/%'" );
            
            foreach ( $collection as $cat ) {
                try {
                    $pathArr = explode ( '/', $cat->getPath () );
                    $namePath = '';
                    for($i = 2, $l = sizeof ( $pathArr ); $i < $l; $i ++) {
                        $name = $collection->getItemById ( $pathArr [$i] )
                            ->getName ();
                        $namePath .= (empty ( $namePath ) ? '' : '/') . trim ( $name );
                    }
                    $cat->setNamePath ( $namePath );
                } catch ( Exception $e ) {
                    echo "ERROR: Cat - ";
                    print_r ( $cat );
                    continue;
                }
            }
            
            $cache = array ();
            foreach ( $collection as $cat ) {
                $cache [strtolower ( $cat->getNamePath () )] = $cat;
                $cat->unsNamePath ();
            }
            $this->_categoryCache [$store->getId ()] = $cache;
        }
        $cache = &$this->_categoryCache [$store->getId ()];
        
        $catIds = array ();
        foreach ( explode ( ',', $categories ) as $categoryPathStr ) {
            $categoryPathStr = preg_replace ( '#s*/s*#', '/', trim ( $categoryPathStr ) );
            if (! empty ( $cache [$categoryPathStr] )) {
                $catIds [] = $cache [$categoryPathStr]->getId ();
                continue;
            }
            $path = $rootPath;
            $namePath = '';
            foreach ( explode ( '/', $categoryPathStr ) as $catName ) {
                $namePath .= (empty ( $namePath ) ? '' : '/') . strtolower ( $catName );
                if (empty ( $cache [$namePath] )) {
                    $cat = Mage::getModel ( 'catalog/category' )->setStoreId ( $store->getId () )
                        ->setPath ( $path )
                        ->setName ( $catName )
                        ->setIsActive ( 1 )
                        ->save ();
                    $cache [$namePath] = $cat;
                }
                $catId = $cache [$namePath]->getId ();
                $path .= '/' . $catId;
            }
            if ($catId) {
                $catIds [] = $catId;
            }
        }
        return join ( ',', $catIds );
    }
    
    protected function _removeFile($file) {
        if (file_exists ( $file )) {
            if (unlink ( $file )) {
                return true;
            }
        }
        return false;
    }
    
    protected function _chkTitle($title, &$options) {
        
        if ($title) {
            foreach($options as $item) {
                if ($item['title'] == $title) {
                    return true;
                }
            }
        }
        return false;
    }
    
    private function _getStoreIdByCode($storeCode)
    {

        $store = Mage::getModel('core/store')->loadConfig(trim($storeCode));
        if ($store){
            return $store->getId();
        }else {
            return false;
        }
    }
    
    private function _getIds($ids)
    {
        if (is_string($ids)) {
            $ids = explode(',', $ids);
        } elseif (!is_array($ids)) {
            return array();
        }
        
        foreach ($ids as $i=>$v) {
            $ids[$i] =$this->_getStoreIdByCode($v);
            if(empty($ids[$i])) {
                unset($ids[$i]);
                Mage::throwException ("Reviews store code[{$v}] error !");
            }
        }
        return $ids;
    }
}
